<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of owlproduct
 *
 * @author trung
 */

if (!defined(INT_JOUR_PAPER))
    define('INT_JOUR_PAPER', 'International Journal Paper');
if (!defined(NAT_JOUR_PAPER))
    define('NAT_JOUR_PAPER', 'National Journal Paper');
if (!defined(INT_CONF_PAPER))
    define('INT_CONF_PAPER', 'International Conference Paper');
if (!defined(NAT_CONF_PAPER))
    define('NAT_CONF_PAPER', 'National Conference Paper');

class Owl_Product extends Owl_Db{
    
    function Owl_Product(){
        $this->Owl_Db('product');
    }

    function get_all_products($type = false){
        if ($type) {
            return $this->get_results("//product[type = '$type']");
        }
        else {
            return $this->get_results('//product');
        }
    }

    function get_product($product_name){
        if ( empty($product_name) )
            return false;
        return $this->get_row('/products/product[name="'.$product_name.'"]');
    }

    function insert_products($data){

        if ($this->get_product($data['name']) !== false ) {
            $this->last_error = new Owl_Error('504', __('Product name is duplicate'));
            return false;
        }
        $defaults = array(
                            'name' => '',
                            'type' => 'Paper',
                            'link' => '',
                            'year' => Owl_Date_Time::get_current_year(),
                            'description' => ''
                        );

        $data = Owl_System_Helper::array_merge($data, $defaults);        
        return $this->insert('/products', 'product', $data);
    }

    function delete_products($product_name){
        if ( empty($product_name) )
            return false;
        return $this->delete('/products/product[name="'.$product_name.'"]');
    }

    function update_products($product_name, $data){
        if ( empty($product_name) )
            return false;
        $old_product = $this->get_product($product_name);
        if ($old_product === false){
            $this->last_error = new Owl_Error('504', 'Product does not exist');
            return false;
        }
        
        $defaults = array(
                            'name' => $old_product['name'],
                            'type' => $old_product['type'],
                            'link' => $old_product['link'],
                            'year' => $old_product['year'],
                            'description' => $old_product['description']
                        );
        $data = Owl_System_Helper::array_merge($data, $defaults);
        return $this->update('/products/product[name="'.$product_name.'"]','product',$data);
    }

    function get_product_for_widget($type, $num) {
        $products = array();
        if ($type == 'paper') {
            $international_journal_papers = $this->get_all_products(INT_JOUR_PAPER);
            $national_journal_papers = $this->get_all_products(NAT_JOUR_PAPER);
            $international_conference_papers = $this->get_all_products(INT_CONF_PAPER);
            $national_conference_papers = $this->get_all_products(NAT_CONF_PAPER);
            $products = array_merge($international_journal_papers, $products);
            $products = array_merge($national_journal_papers, $products);
            $products = array_merge($international_conference_papers, $products);
            $products = array_merge($national_conference_papers, $products);
            $products = array_slice($this->sort_products($products), 0, $num);
            $to_print = array();
            foreach($products as $product) {
                if (!empty($product["link"])) {
                    $to_print[] = Owl_Html::make_it_link(Owl_Link::site_url(false) . $product['link'], __($product['name'], true));
                }
                else {
                    $to_print[] = Owl_Html::make_it_link(Owl_Link::template_url('product', false) . "#papers", __($product['name'], true));
                }
            }
            if (!empty($to_print)) {
                return Owl_Html::make_it_list($to_print);
            }
            else {
                return __("No information");
            }
        }
        else {
            $products = $this->get_all_products('Project');
            $products = array_slice($this->sort_products($products), 0, $num);
            foreach($products as $product) {
                if (!empty($product["link"])) {
                    $to_print[] = Owl_Html::make_it_link($product['link'], __($product['name'], true));
                }
                else {
                    $to_print[] = Owl_Html::make_it_link(Owl_Link::template_url('product', false) . "#projects", __($product['name'], true));
                }
            }
            if (!empty($to_print)) {
                return Owl_Html::make_it_list($to_print);
            }
            else {
                return __("No information");
            }
        }
    }

    function get_product_with_lang($product_name, $lang) {
        $product = $this->get_product($product_name);
        if ($product == false) {
            return false;
        }
        $owl_ulang = new Owl_Ulang();
        $name_translator = $owl_ulang->get_ulang($product["name"]);
        if ($name_translator == false) {
            return false;
        }
        $name_translated = ($name_translator[$lang]) ? $name_translator[$lang] : "" ;
        $description_translator = $owl_ulang->get_ulang($product["description"]);
        if ($description_translator == false) {
            return false;
        }
        $description_translated = ($description_translator[$lang]) ? $description_translator[$lang] : "";
        return array($name_translated, $description_translated);
    }

    function get_max_id() {
        $products = $this->get_all_products();
        $name = array();
        foreach($products as $product) {
            $name[] = $product["name"];
        }
        array_multisort($name, SORT_DESC, $products);
        $max_name = explode(" ", $products[0]["name"]);
        return ($max_name[1] + 1);
    }

    function print_body($type, $data) {
        $to_print = array();
        $to_print[] = "<b>" . __(ucwords($type) . "'s name") . "</b>: " . Owl_Format::esc_html(__($data["name"], true));
        $to_print[] = "<b>" . __("Type") . "</b>: " . __($data["type"]);
        if ($type == 'paper') {
            if (empty ($data["link"])) {
                $to_print[] = "<b>" . __("Link") . "</b>: " ;
            }
            else {
                $to_print[] = "<b>" . __("Link") . "</b>: " . Owl_HTML::make_it_link(Owl_Link::site_url(false) . $data["link"], __('Download'));
            }
        }
        else {
            $to_print[] = "<b>" . __("Link") . "</b>: " . Owl_Format::make_clickable($data["link"]);
        }
        $to_print[] = "<b>" . __("Year") . "</b>: " . $data["year"];
        $to_print[] = "<b>" . __("Description") . "</b>: " . Owl_Format::make_nice_textarea_content(Owl_Format::esc_html(__($data["description"], true)));
        echo Owl_Html::make_it_list($to_print);
    }

    function print_form($type, $data = array()) {
        if (empty($data)) {
            echo '<form action="' . Owl_Link::ajax_url(false) . 'product-ajax.php" method="POST">';
        }
        else {
            echo '<form action="' . Owl_Link::ajax_url(false) . 'product-ajax.php" method="POST">';
        }
        Owl_Form::print_hidden(array(
            "name" => "type",
            "value" => $type
        ));
        if (empty($data)) {
            Owl_Form::print_hidden(array(
                "name" => "action",
                "value" => "add_product"
            ));
        }
        else {
            Owl_Form::print_hidden(array(
                "name" => "action",
                "value" => "edit_product"
            ));
            Owl_Form::print_hidden(array(
                "name" => "old_name",
                "value" => $data["name"]
            ));
        }
        echo '<table class="form-table" border="0" cellpadding="0" cellspacing="0">';
        echo '<tbody>';

        //Language
        echo '<tr>';
        echo '<th>';
        Owl_Form::print_label(array(
            'value' => __("Language")
        ));
        echo '</th>';
        echo '<td>';
        if (empty($data)) {
            Owl_Form::print_combo_box(array(
                'name' => 'lang',
                'value' => get_current_language(),
                'options' => Owl_Functions::get_available_languages()
            ));
        }
        else {
            Owl_Form::print_combo_box(array(
                'name' => 'lang',
                'value' => get_current_language(),
                'options' => Owl_Functions::get_available_languages(),
                'class' => 'form-combobox input-lang-changer'
            ));
        }
        echo '</td>';
        echo '</tr>';

        //Name
        echo '<tr>';
        echo '<th>';
        Owl_Form::print_label(array(
            'value' => __(ucwords($type)  . "'s name"),
            'required' => true
        ));
        echo '</th>';
        echo '<td>';
        Owl_Form::print_textbox(array(
            'name' => 'product_name',
            'value' => Owl_Format::esc_html(__($data["name"], true, true)),
            'class' => 'form-textbox ' . Owl_Functions::build_validate_string(array('required'))
        ));
        echo '</td>';
        echo '</tr>';

        //Type
        if ($type == 'paper') {
            echo '<tr>';
            echo '<th>';
            Owl_Form::print_label(array(
                'value' => __("Type")
            ));
            echo '</th>';
            echo '<td>';

            $value = null;
            switch ($data['type']) {
                case INT_JOUR_PAPER :
                    $value = 0;
                    break;
                case NAT_JOUR_PAPER :
                    $value = 1;
                    break;
                case INT_CONF_PAPER :
                    $value = 2;
                    break;
                case NAT_CONF_PAPER :
                    $value = 3;
                    break;
                default:
                    $value = 0;
                    break;
            }

            Owl_Form::print_combo_box(array(
                'name' => 'product_type',
                'value' => $value,
                'options' => array(
                    0 => __(INT_JOUR_PAPER),
                    1 => __(NAT_JOUR_PAPER),
                    2 => __(INT_CONF_PAPER),
                    3 => __(NAT_CONF_PAPER)
                )
            ));
            echo '</td>';
            echo '</tr>';
        }

        //Link
        echo '<tr>';
        echo '<th>';
        Owl_Form::print_label(array(
            'value' => __("Link")
        ));
        echo '</th>';
        echo '<td>';
        if ($type == 'paper') {
            $value = (empty ($data["link"])) ? '' : Owl_Link::site_url(false) . $data['link'];
            Owl_Form::print_file_select(array(
                'name' => 'paper_file',
                'value' => $value,
                'label' => __('Old file')
            ));
        }
        else {
            Owl_Form::print_textbox(array(
                'name' => 'product_link',
                'value' => $data["link"],
                'class' => 'form-textbox ' . Owl_Functions::build_validate_string(array('url'))
            ));
        }
        echo '</td>';
        echo '</tr>';

        //Year
        echo '<tr>';
        echo '<th>';
        Owl_Form::print_label(array(
            'value' => __("Year")
        ));
        echo '</th>';
        echo '<td>';
        $current_year = Owl_Date_Time::get_current_year();
        $year_data = array();
        for ($year = $current_year - 20; $year <= $current_year + 5; $year++) {
            $year_data["$year"] = "$year";
        }
        $value = (empty($data)) ? $current_year : $data["year"];
        
        Owl_Form::print_combo_box(array(
            'name' => 'product_year',
            'value' => $value,
            'options' => $year_data
        ));
        echo '</td>';
        echo '</tr>';

        //Description
        echo '<tr>';
        echo '<th>';
        Owl_Form::print_label(array(
            'value' => __("Description")
        ));
        echo '</th>';
        echo '<td>';
        Owl_Form::print_textarea(array(
            'name' => 'product_description',
            'value' => Owl_Format::esc_html(__($data["description"], true, true)),
            'rows' => 5
        ));
        echo '</td>';
        echo '</tr>';

        //Ajax feedback
        echo '<tr>';
        echo '<td colspan="2">';
        Owl_Default_Content::print_ajax_feedback(false);
        echo '</td>';
        echo '</tr>';

        //Button
        echo '<tr>';
        echo '<td class="form-button-pane" colspan="2">';
        echo '<img src="' . Owl_Link::image_url(false) . 'default/ajax-load.gif" class="ajax-load" alt="Ajax load" />';
        if (empty($data)) {
            Owl_Form::print_button(array(
                'name' => 'submitForm',
                'value' => __('Save'),
                'class' => 'form-button product-add-ajax-submit',
            ));
            Owl_Form::print_button(array(
                'name' => 'cancel',
                'value' => __('Cancel'),
                'class' => 'form-button product-add-cancel',
            ));
        }
        else {
            Owl_Form::print_button(array(
                'name' => 'submitForm',
                'value' => __('Save'),
                'class' => 'form-button product-edit-ajax-submit',
            ));
            Owl_Form::print_button(array(
                'name' => 'delete',
                'value' => __('Delete'),
                'class' => 'form-button product-delete-ajax-submit',
            ));
            Owl_Form::print_button(array(
                'type' => 'reset',
                'name' => 'cancel',
                'value' => __('Cancel'),
                'class' => 'form-button product-edit-cancel',
            ));
        }
        echo '</td>';
        echo '</tr>';
        
        echo '</tbody>';
        echo '</table>';
        echo '</form>';
    }

    function print_form_control() {
        echo '<a href="#" class="product-form-toggle">';
        echo '<span >' . __("Edit"). '</span>';
        echo '</a>';
        echo '<a href="#" class="product-form-close">';
        echo '<span >' . __("Close") . '</span>';
        echo '</a>';
    }

    function print_papers() {
        $user = Owl_User::get_instance();

        echo '<h3>' . __('Publications') . '</h3>';
        if ($user->is_logged_in()) {
            echo '<div>';
            echo '<div id="paper-add-form" class="form-container hidden">';
            $this->print_form("paper");
            echo '</div>';
            echo '<div id="paper-add-form-controller" class="product-form-controller">';
            echo '<a href="#" class="product-add-form-toggle info-extra add"><span>' .__("Add") . '</span></a>';
            echo '</div>';
            echo '</div>';
        }
        echo '<div id="papers-container">';
        $this->print_papers_main();
        echo '</div>';
    }

    function print_papers_main() {
        $international_journal_papers = $this->get_all_products(INT_JOUR_PAPER);
        $national_journal_papers = $this->get_all_products(NAT_JOUR_PAPER);
        $international_conference_papers = $this->get_all_products(INT_CONF_PAPER);
        $national_conference_papers = $this->get_all_products(NAT_CONF_PAPER);
        $user = Owl_User::get_instance();

        //International journal papers
        if (!empty ($international_journal_papers)) {
            echo '<h4>' . __(INT_JOUR_PAPER . 's') . '</h4>';
            $this->print_products_by_type('paper', $international_journal_papers, $user->is_logged_in());
        }

        //National journal papers
        if (!empty ($national_journal_papers)) {
            echo '<h4>' . __(NAT_JOUR_PAPER . 's') . '</h4>';
            $this->print_products_by_type('paper', $national_journal_papers, $user->is_logged_in());
        }

        //International conference papers
        if (!empty ($international_conference_papers)) {
            echo '<h4>' . __(INT_CONF_PAPER . 's') . '</h4>';
            $this->print_products_by_type('paper', $international_conference_papers, $user->is_logged_in());
        }

        //National conference papers
        if (!empty ($national_conference_papers)) {
            echo '<h4>' . __(NAT_CONF_PAPER . 's') . '</h4>';
            $this->print_products_by_type('paper', $national_conference_papers, $user->is_logged_in());
        }
    }

    function print_projects() {
        $user = Owl_User::get_instance();

        echo '<h3>' . __('Projects') . '</h3>';
        if ($user->is_logged_in()) {
            echo '<div>';
            echo '<div id="project-add-form" class="form-container hidden">';
            $this->print_form("project");
            echo '</div>';
            echo '<div id="project-add-form-controller" class="product-form-controller">';
            echo '<a href="#" class="product-add-form-toggle info-extra add"><span>' .__("Add") . '</span></a>';
            echo '</div>';
            echo '</div>';
        }
        echo '<div id="projects-container">';
        $this->print_projects_main();
        echo '</div>';
    }

    function print_projects_main() {
        $projects = $this->get_all_products('Project');
        $current_projects = array();
        $previous_projects = array();
        foreach ($projects as $project) {
            if ($project['year'] >= OWL_Date_Time::get_current_year()) {
                $current_projects[] = $project;
            }
            else {
                $previous_projects[] = $project;
            }
        }
        $user = Owl_User::get_instance();

        if (!empty ($current_projects)) {
            echo '<h4>' . __('Current projects') . '</h4>';
            $this->print_products_by_type('project', $current_projects, $user->is_logged_in());
        }
        if (!empty ($previous_projects)) {
            echo '<h4>' . __('Previous projects') . '</h4>';
            $this->print_products_by_type('project', $previous_projects, $user->is_logged_in());
        }
    }

    function print_products_by_type($type, $data, $loged_in = false) {
        $data = $this->sort_products($data);
        if ($loged_in) {
            foreach ($data as $pos=>$product) {
                if($pos == (count($data) - 1))
                    echo '<div class="product-row last">';
                else
                    echo '<div class="product-row">';
                echo '<div class="product-body">';
                $this->print_body($type, $product);
                echo '</div>';
                echo '<div class="form-container hidden">';
                $this->print_form($type, $product, $pos);
                echo '</div>';
                echo '<div class="form-controller">';
                $this->print_form_control();
                echo '</div>';
                echo '</div>';
            }
        }
        else {
            foreach ($data as $pos=>$paper) {
                if($pos == (count($data) - 1))
                    echo '<div class="product-row last">';
                else
                    echo '<div class="product-row">';
                echo '<div class="product-body">';
                $this->print_body($type, $paper);
                echo '</div>';
                echo '</div>';
            }
        }
    }

    function sort_products($products) {
        $order = (get_option('product_sort', 1)) ? SORT_DESC : SORT_ASC;
        $year = array();
        foreach($products as $product) {
            $year[] = $product["year"];
        }
        array_multisort($year, $order, $products);
        return $products;
    }
}

